from rest_framework import serializers
from apps.goods.models import SKUImage
from apps.meiduo_admin.utils import upload_image_to_qiniu


class SKUImageModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKUImage
        fields = '__all__'

    def update(self, instance, validated_data):
        # TODO 1. 获取图片二进制
        file = validated_data.get('image')
        if file:
            file_data = file.read()
            # TODO 2. 上传到七牛云
            new_image = upload_image_to_qiniu(file_data)
            # TODO 3. 更新数据
            instance.image = new_image
        instance.sku_id = validated_data.get('sku', instance.sku_id)
        instance.save()

        return instance


from apps.goods.models import SKU


# SKU的序列化器
class SKUModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ['id', 'name']
